<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>轮播</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        .main {
            width: 300px;
            overflow: hidden;

        }

        .img_bg {
            display: flex;
            align-items: flex-start;
            transition: all 0.5s;
        }

        .img_bg > img {
            vertical-align: top;
        }

        .red {
            color: red;
        }
    </style>
</head>
<body>
<div id="main_body">
    <div class="main">
        <div id="img_bg" class="img_bg">
            <img src="https://fthmb.tqn.com/0ui_Zw01Ht9NHJkSBlqOIC1IH44=/960x0/filters:no_upscale()/yorkshire-terrier-583788122-581630e85f9b581c0b018a00.jpg"
                 alt="" width="300" height="200">
            <img src="https://canna-pet.com/wp-content/uploads/2017/06/20-longest-living-dog-breeds_canna-pet-e1498599846169.jpg"
                 alt="" width="300" height="200">
            <img src="https://fthmb.tqn.com/0ui_Zw01Ht9NHJkSBlqOIC1IH44=/960x0/filters:no_upscale()/yorkshire-terrier-583788122-581630e85f9b581c0b018a00.jpg"
                 alt="" width="300" height="200">
            <img src="https://canna-pet.com/wp-content/uploads/2017/06/20-longest-living-dog-breeds_canna-pet-e1498599846169.jpg"
                 alt="" width="300" height="200">
        </div>
    </div>
    <div class="btn">
        <span class="red">第一张</span>
        <span>第二张</span>
        <span>第三张</span>
        <span>第四张</span>
    </div>
</div>
<script>
    let btn = document.querySelectorAll('.btn > span');
    let flg = 0;
    let btn_length = btn.length;
    let Timer;

    Autoplay();

    for (let i = 0; i < btn.length; i++) {//鼠标点击事件
        btn[i].index = i;
        btn[i].onclick = function () {
            clear_classname();
            flg = this.index;
            //保证点击和自动播放的顺序是相同的，例：自动播放到第三手动点第一，按理自动播放应从第二继续，不设置的话自动播放会到第四

            img_bg.style.transform = 'translate(' + flg * -300 + 'px)';
            //console.log(this.index);
            //console.log(flg);
            //console.log(btn[i].index);
            btn[flg].classList.add('red');
        }
    }

    function Autoplay() {//自动播放
        Timer = setInterval(function () {
            flg += 1;
            if (flg === btn_length) {//到最后一张恢复从0，即第一个再开始
                flg = 0;
            }
            clear_classname();
            //console.log(flg);
            img_bg.style.transform = 'translate(' + flg * -300 + 'px)';
            btn[flg].classList.add('red');
        }, 1500);
    }

    function clear_classname() {//设置当前红色前，清空之前设置的红色
        for (let i = 0; i < btn.length; i++) {
            btn[i].classList.remove('red');
        }
    }

    main_body.onmousemove = function () {//鼠标移入清除定时器
        clearInterval(Timer);
    };

    main_body.onmouseout = function () {//鼠标移出还原定时器
        Autoplay();
    };
</script>
</body>
</html>